package com.suncky.example.activity

import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.suncky.example.R
import com.suncky.example.databinding.ActivityWaterMakerBinding
import com.suncky.frame.base.BaseViewBindingActivity
import com.suncky.frame.base.adapter.ImageEditGridAdapter
import com.suncky.frame.base.adapter.RecyclerViewAdapter
import com.suncky.frame.base.adapter.holder.RecyclerViewHolder
import com.suncky.frame.dialog.ImageViewerDialog
import com.suncky.frame.utils.ToastUtils
import com.suncky.frame.utils.glide.GlideUtils
import com.suncky.frame.utils.image.ImageWaterMaker
import com.suncky.frame.utils.image.ImageWaterMaker.Gravity
import com.suncky.frame.widget.recyclerview.GridDividerItemDecoration
import com.zhihu.matisse.Matisse
import com.zhihu.matisse.MimeType
import com.zhihu.matisse.engine.impl.GlideEngine
import com.zhihu.matisse.internal.entity.CaptureStrategy
import java.io.File

class WaterMakerActivity : BaseViewBindingActivity<ActivityWaterMakerBinding>() {

    var markerImagePath: String? = null
    private val textAdapter by lazy { StringListAdapter(context,null) }
    private val imageViewerDialog by lazy { object:ImageViewerDialog<String>(context,null){
        override fun onGetDesc(item: String?, position: Int): String? {
            return null
        }

        override fun onShowImage(item: String?, position: Int, imageView: ImageView?) {
            GlideUtils.load(context,item,imageView, com.suncky.frame.R.drawable.ic_aframe_def_img)
        }

    } }
    private val imageAdapter by lazy { object :ImageEditGridAdapter(context,null){
        override fun onGetImageUrl(item: String?, position: Int): String? {
            return item
        }

        override fun onAddImage(position: Int) {
            super.onAddImage(position)
            Matisse.from(this@WaterMakerActivity)
                ///选择视频和图片
                // 另：选择图片：MimeType.ofImage() ；选择视频：MimeType.ofVideo() ；
                //	 自定义选择选择的类型： MimeType.of(MimeType.JPEG,MimeType.AVI...)
                .choose(MimeType.ofImage())
                .theme(com.zhihu.matisse.R.style.Matisse_Dracula)
                //countable属性 true:显示数字,false:显示一个√
                .countable(true)
                .capture(true)
                .maxSelectable(9)
                .thumbnailScale(0.85f)
                .imageEngine(GlideEngine())
                .captureStrategy(
                    CaptureStrategy(true,
                        context.applicationInfo.packageName + ".provider")
                )
                .forResult(2)
        }

        override fun onViewImage(item: String?, position: Int) {
            super.onViewImage(item, position)
            imageViewerDialog.open(position)
        }

    } }

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)
        binding.rvMarkerTexts.layoutManager = LinearLayoutManager(context)
        binding.rvMarkerTexts.adapter = textAdapter
        binding.rvImage.addItemDecoration(
            GridDividerItemDecoration(
                25,
                Color.TRANSPARENT,
                GridDividerItemDecoration.VERTICAL
            )
        )
        binding.rvImage.layoutManager = GridLayoutManager(context, 3)
        binding.rvImage.adapter = imageAdapter
        binding.tvAddText.setOnClickListener(this)
        binding.tvAddImage.setOnClickListener(this)

        textAdapter.data = listOf("箭头函数的返回类型可以省略，此时返回类型由函数体推断。",
            "可以通过编写重载，指定函数的不同调用方式。具体方法是，为同一个函数写入多个同名但签名不同的函数头，函数实现紧随其后。",
            "方法属于类。类可以定义实例方法或者静态方法。静态方法属于类本身，只能访问静态字段。而实例方法既可以访问静态字段，也可以访问实例字段，包括类的私有字段。")
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            1->{
                if (resultCode == RESULT_OK && data != null) {
                    markerImagePath = Matisse.obtainPathResult(data)[0]
                    GlideUtils.load(context,markerImagePath,binding.ivMarkerImage,
                        com.suncky.frame.R.drawable.ic_aframe_def_img)
                }
            }
            2->{
                if (resultCode != RESULT_OK || data == null) {
                    return
                }
                val path = Matisse.obtainPathResult(data)
                val uris = Matisse.obtainResult(data)
                var index = 0
                val files = arrayOfNulls<File>(path.size)
                while (path.size > index) {
                    files[index] = File(path[index])
                    ++index
                }
                val markerImage = BitmapFactory.decodeFile(markerImagePath)
                ImageWaterMaker.with(context).source(path).alpha(150).space(20).margin(30).gravity(Gravity.LEFT_BOTTOM).position(80,160)
                    .waterMarkerText(textAdapter.data)
                    .textSize(resources.getDimension(com.suncky.frame.R.dimen.sp_48))
                    .textLineSpaceMulti(1.0f)
                    .waterMarkerImage(markerImage)
                    .callback(object:ImageWaterMaker.WaterMakerCallback{
                        override fun onStart() {
                            showLoadingPop()
                        }

                        override fun onSuccess(vararg results: File) {
                            dismissLoadingPop()
                            imageAdapter.setImage(results.flatMap { listOf(it.absolutePath) })
                            imageViewerDialog.imageData = imageAdapter.data
                        }

                        override fun onError(throwable: Throwable?, vararg path: String?) {
                            dismissLoadingPop()
                            ToastUtils.toast(throwable?.message)
                        }

                    }).launch()
            }
        }
    }

    override fun onSingledClick(v: View?) {
        super.onSingledClick(v)
        when (v?.id) {
            binding.tvAddText.id->{
                val text = binding.edtText.text.toString().trim()
                if (text.isNotEmpty()) {
                    textAdapter.appendData(text)
                    binding.edtText.setText(null)
                }
            }
            binding.tvAddImage.id->{
                Matisse.from(this)
                    ///选择视频和图片
                    // 另：选择图片：MimeType.ofImage() ；选择视频：MimeType.ofVideo() ；
                    //	 自定义选择选择的类型： MimeType.of(MimeType.JPEG,MimeType.AVI...)
                    .choose(MimeType.ofImage())
                    .theme(com.zhihu.matisse.R.style.Matisse_Dracula)
                    //countable属性 true:显示数字,false:显示一个√
                    .countable(false)
                    .capture(false)
                    .maxSelectable(1)
                    .thumbnailScale(0.85f)
                    .imageEngine(GlideEngine())
                    .captureStrategy(
                        CaptureStrategy(true,
                        context.applicationInfo.packageName + ".provider")
                    )
                    .forResult(1)
            }
        }
    }

    class StringListAdapter(context: Context, data: List<String>?) : RecyclerViewAdapter<String>(context,
        data, R.layout.item_string_list) {

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerViewHolder {
            val holder = super.onCreateViewHolder(parent, viewType)
            val textView = holder.getView<TextView>(R.id.text)
            textView.gravity = android.view.Gravity.START
            textView.setPadding(15,10,15,10)
            return holder
        }

        override fun convert(holder: RecyclerViewHolder?, item: String?, position: Int) {
            holder?.setText(R.id.text, item)//显示内容
        }
    }
}
